<?php

namespace App\Exports;

use App\Models\FinanceTransferRecord;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Support\Carbon;
use Maatwebsite\Excel\Concerns\FromQuery;

class TransferRecordExport extends BaseExport implements FromQuery
{
    public function headings(): array
    {
        return [
            '订单号',
            '状态',
            '渠道',
            '供应商',
            '金额（元）',
            '汇总户余额（元）',
            '时间',
        ];
    }

    public function map($row): array
    {
        $row = $row->toArray();
        return [
            $row['order_id'], // 订单号
            FinanceTransferRecord::STATUS_MAP[$row['status']], // 状态
            '厦门国际银行', // 渠道
            $row['target_type'] === FinanceTransferRecord::TARGET_TYPE_SUPPLIER ? ($row['subject']['name'] ?? '') : '一般对公户', // 供应商
            number_format(-1 * ($row['amount'] / 100), 2), // 金额（元）
            number_format($row['balance'] / 100, 2), // 汇总户余额（元）
            $row['created_at'], // 时间
        ];
    }

    public function query()
    {
        return FinanceTransferRecord::query()
            ->with(['subject'])
            ->when($this->request['name'] ?? '', function (Builder $builder, $name) {
                $builder
                    ->join('finance_suppliers', 'finance_suppliers.id', '=', 'finance_transfer_records.subject_id')
                    ->where('finance_suppliers.name', 'like', "%$name%");
            })
            ->when($this->request['order_id'] ?? 0, function (Builder $builder, $orderId) {
                $builder->where('finance_transfer_records.order_id', 'like', "%$orderId%");
            })
            ->when($this->request['status'] ?? 0, function (Builder $builder, $status) {
                $builder->where('finance_transfer_records.status', $status);
            })
            ->when($this->request['created_at_begin'] ?? '', function (Builder $builder, $createdAtBegin) {
                $builder->where('finance_transfer_records.created_at', '>=', $createdAtBegin);
            })
            ->when($this->request['created_at_end'] ?? '', function (Builder $builder, $createdAtEnd) {
                $builder->where('finance_transfer_records.created_at', '<=', Carbon::parse($createdAtEnd)->endOfDay());
            })
            ->select(['finance_transfer_records.*']);
    }
}
